<template>
	<view class="upload-content">
		<view v-if="list.length" class="pic-wrap">
			<view v-for="(pic, j) in list" :key="j" class="pic-item">
				<image class="clear-btn" mode="aspectFill" :src="clearIcon"
					@click="handleClearImg(j)"></image>
				<image class="pic-dom" mode="aspectFill" :src="pic.url"
					@click="handleViewPic(pic.url)"></image>
			</view>
		</view>
		<view v-else>
			<image class="upload-btn" mode="aspectFit" :src="uploadIcon"
				@click="handleSelectImg"></image>
		</view>
	</view>
</template>
<script>
	import clearIcon from '@/static/components/close-upload-icon.png';
	import uploadIcon from '@/static/components/upload-icon.png';
	import {
		uploadFile
	} from '@/api/common.js';
	export default {
		name: 'UploadImgCommon',
		props: {
			value: {
				type: Array,
				required: true,
				default: function() {
					return [];
				},
			},
		},
		data() {
			return {
				clearIcon,
				uploadIcon,
				list: [],
			};
		},
		watch: {
			value: {
				handler: function(value) {
					this.list = [...value];
				},
				immediate: true,
				deep: true,
			},
		},
		methods: {
			handleSelectImg() {
				try {
					uni.chooseImage({
						count: 1,
						sourceType: ['album', 'camera'],
						success: async (res) => {
							const imgList = [];
							const tempFilePaths = res.tempFilePaths;
							// 上传图片临时路径
							tempFilePaths.map((path) => {
								imgList.push(uploadFile(path));
							});
							const resLoaded = await Promise.all(imgList);
							console.log(resLoaded);
							const imgloadedList = resLoaded.map((item) => ({
								url: item.picUrl,
								name: item.picName
							}));
							this.list.push(...imgloadedList);
							this.$emit('input', [...this.list]);
						},
					});
				} catch (e) {
					console.log(e);
				}
			},
			handleClearImg(j) {
				this.list.splice(j, 1);
				this.$emit('input', [...this.list]);
			},
			handleViewPic(picPath) {
				// 预览图片
				uni.previewImage({
					urls: [picPath],
				});
			},
		},
	};
</script>
<style scoped lang="scss">
	.pic-wrap {
		width: 100%;
		height: 100%;
	}

	.pic-item {
		position: relative;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 240rpx;
		height: 240rpx;
	}

	.pic-dom {
		width: 100%;
		height: 100%;
	}

	.pic-close-btn {
		position: absolute;
		top: 12rpx;
		right: 12rpx;
	}

	.upload-btn {
		width: 240rpx;
		height: 240rpx;
	}

	.clear-btn {
		position: absolute;
		top: 4rpx;
		right: 4rpx;
		width: 44rpx;
		height: 44rpx;
	}
</style>